package hust.ioic.oa.view.listener;

import hust.ioic.oa.domain.Department;
import hust.ioic.oa.domain.Operator;
import hust.ioic.oa.domain.Rdfile;
import hust.ioic.oa.service.OperatorService;
import hust.ioic.oa.service.RdfileService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.gson.Gson;

public class GsonServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		WebApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		Gson gson = new Gson();
		String sid = req.getParameter("num");
		String[] sarray = sid.split(",");
		int id = Integer.parseInt(sarray[1]);
		int operatorId = Integer.parseInt(sarray[0]);
		RdfileService rdfileService = (RdfileService) ac
				.getBean("rdfileServiceImpl");
		OperatorService os = (OperatorService) ac
				.getBean("operatorServiceImpl");
		Operator o = os.getById(operatorId);
		Rdfile rd = rdfileService.getById(id);
		Set<Department> departments = rd.getDepartments();
		List<Integer> list = new ArrayList<>();

		for (Department d1 : departments) {
			list.add(d1.getId());
		}
		Department d = o.getDepartment();
		List<String> rl = new ArrayList<>();

		if (o.getIsAdmin() == 1 || rd.getOperatorId() == id) {
			rl.add("" + 1);
		} else if (list.contains(d.getId())) {
			rl.add("" + 1);
		} else {
			rl.add("" + 0);
			rl.add(rd.getPassword());
		}
		String result = gson.toJson(rl);
		resp.setContentType("application/json; charset=utf-8");

		resp.setHeader("pragma", "no-cache");
		resp.setHeader("cache-control", "no-cache");

		PrintWriter out = resp.getWriter();

		out.println(result);

		out.flush();
	}

}
